<template>
  <el-dialog
    v-model="visible"
    :title="$t('product.select')"
    top="100px"
    :append-to-body="visible"
    :close-on-click-modal="false"
    width="60%"
  >
    <el-form
      :inline="true"
      :model="dataForm"
      class="demo-form-inline"
      @submit.prevent
    >
      <el-form-item :label="$t('product.prodName')">
        <el-input
          v-model="prodName"
          :placeholder="$t('product.prodName')"
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t('coupon.categoryParent')">
        <el-cascader
          v-model="selectedCategory"
          expand-trigger="hover"
          :options="categoryList"
          :props="categoryTreeProps"
          :clearable="true"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn primary-btn"
          @click="searchProd"
        >
          {{ $t("coupon.query") }}
        </div>
        <div
          class="default-btn"
          @click="clean"
        >
          {{ $t("product.reset") }}
        </div>
      </el-form-item>
    </el-form>
    <div class="prods-select-body">
      <el-table
        ref="prodTableRef"
        v-loading="dataListLoading"
        :data="dataList"
        header-cell-class-name="table-header"
        row-class-name="table-row"
        height="500"
        :row-key="getRowKeys"
        style="width: 100%"
        @selection-change="selectChangeHandle"
        @select="selectHandle"
        @select-all="selectAll"
      >
        <el-table-column
          v-if="isSingle"
          width="50"
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <div>
              <el-radio
                v-model="singleSelectProdId"
                :label="scope.row.prodId"
                @change="getSelectProdRow(scope.row)"
              >
                &nbsp;
              </el-radio>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="!isSingle"
          type="selection"
          header-align="center"
          align="center"
          width="50"
        />
        <el-table-column
          prop="prodName"
          header-align="center"
          align="center"
          :label="$t('coupon.commodityName')"
        />
        <el-table-column
          align="center"
          width="140"
          :label="$t('product.pic')"
        >
          <template #default="scope">
            <ImgShow
              :src="scope.row.pic"
              :img-style="{width:'100px',height:'100px'}"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
        />
      </div>
    </div>
    <template #footer>
      <div>
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t("coupon.cancel") }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="submitProds()"
        >
          {{ $t("coupon.confirm") }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { treeDataTranslate, idList } from '@/utils'
import { ElMessage } from 'element-plus'
const emit = defineEmits(['refreshSelectProds', 'refreshSelectProds'])
const props = defineProps({
  isSingle: {
    default: false,
    type: Boolean
  },
  prodType: {
    default: null,
    type: Number
  },
  dataUrl: {
    default: '/platform/search/prod/page',
    type: String
  }
})

const visible = ref(false)
const dataForm = reactive({
  product: ''
})
const singleSelectProdId = ref(0)
const selectProds = ref([])
const dataList = ref([])
const pageIndex = ref(1)
const pageSize = ref(10)
const totalPage = ref(0)
const dataListLoading = ref(false)
const dataListSelections = ref([])
const prodName = ref(null)
const categoryList = ref([])
const selectedCategory = ref([])
const categoryTreeProps = reactive({
  value: 'categoryId',
  label: 'categoryName'
})
onActivated(() => {
  getDataList()
})

const prodTableRef = ref(null)
onMounted(() => {
  prodTableRef.value?.clearSelection()
})

/**
 * 获取数据列表
 * @param selectProds
 */
const init = (selectProds) => {
  singleSelectProdId.value = 0
  selectProds.value = selectProds
  visible.value = true
  dataListLoading.value = true
  if (selectProds.value) {
    selectProds.value.forEach(row => {
      if (row.prodId) dataListSelections.value.push(row)
    })
  }
  getDataList()
  getCategoryList()
}
defineExpose({ init })

const categoryId = ref(null)
const getCategoryList = () => {
  http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get',
    params: http.adornParams({
      maxGrade: 2,
      status: 1
    })
  }).then(({ data }) => {
    categoryList.value = treeDataTranslate(data, 'categoryId', 'parentId')
  })
}
const getDataList = () => {
  http({
    url: http.adornUrl(props.dataUrl),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageIndex.value,
          size: pageSize.value,
          prodName: prodName.value ? prodName.value : null,
          keyword: prodName.value ? prodName.value : null,
          categoryId: categoryId.value ? categoryId.value : null,
          status: 1,
          prodType: props.prodType,
          isActive: 1 // 过滤掉活动商品
        }
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    totalPage.value = data.total
    dataListLoading.value = false
    if (selectProds.value && selectProds.value.length) {
      nextTick(() => {
        if (dataListSelections.length > 0) {
          dataList.value?.forEach(element => {
            if (dataListSelections.value?.map(item => item.prodId).indexOf(element.prodId) !== -1) {
              prodTableRef.value?.toggleRowSelection(element, true)
            }
          })
        }
      })
    }
  })
}

/**
 * 每页数
 * @param val
 */
const sizeChangeHandle = (val) => {
  pageSize.value = val
  pageIndex.value = 1
  getDataList()
}

/**
 * 当前页
 * @param val
 */
const currentChangeHandle = (val) => {
  pageIndex.value = val
  getDataList()
}

/**
 * 单选商品事件
 * @param row
 */
const getSelectProdRow = (row) => {
  dataListSelections.value = [row]
}

/**
 * 全选
 * @param e
 */
const selectAll = (e) => {
  if (e.length > 0) {
    dataListSelections.value = dataListSelections.value?.filter(value => dataList.value?.map(val => val.prodId).indexOf(value.prodId) === -1)
    dataList.value?.forEach((value) => {
      dataListSelections.value?.push(value)
    })
  } else {
    dataListSelections.value = dataListSelections.value?.filter(value => dataList.value?.map(val => val.prodId).indexOf(value.prodId) === -1)
  }
}

/**
 * 手动勾选数据行的 Checkbox 时触发的事
 * @param selection
 * @param row
 */
const selectHandle = (selection, row) => {
  // 判断是否选中
  const selectionStatu = selection.map(element => element.prodId).indexOf(row.prodId) !== -1
  if (selectionStatu && selection.length > 0 && selection) {
    // 选中添加
    dataListSelections.value?.push(row)
  } else {
    // 未选中删除
    dataListSelections.value = dataListSelections.value?.filter(element => element.prodId !== row.prodId)
  }
}

const getRowKeys = (row) => {
  return row.prodId
}

/**
 * 获取分类id
 */
const handleChange = (val) => {
  categoryId.value = val[val.length - 1]
}

/**
 * 根据条件搜索商品
 */
const searchProd = () => {
  pageIndex.value = 1
  getDataList()
}

/**
 * 清空搜索条件
 */
const clean = () => {
  prodName.value = ''
  categoryId.value = null
  selectedCategory.value = idList(categoryList.value, categoryId.value, 'categoryId', 'children').reverse()
}

/**
 * 确定事件
 */
const submitProds = () => {
  // 商品空选择校验
  if (!dataListSelections.value.length) {
    ElMessage({
      message: $t('marketing.pleaseSelectAProduct'),
      type: 'info',
      duration: 1500
    })
    return
  }
  // 商品单选情况
  if (props.isSingle) {
    dataListSelections.value.length && emit('refreshSelectProds', dataListSelections.value[0])
    // 商品多选情况
  } else {
    const prods = []
    dataListSelections.value.forEach(item => {
      const prodIndex = prods.findIndex((prod) => prod.prodId === item.prodId)
      if (prodIndex === -1) {
        prods.push(
          {
            prodId: item.prodId,
            prodName: item.prodName,
            pic: checkFileUrl(item.pic),
            prodType: item.prodType,
            oriPrice: item.oriPrice,
            price: item.price,
            brief: item.brief,
            activityPrice: item.activityPrice
          }
        )
      }
    })
    emit('refreshSelectProds', prods)
  }
  dataListSelections.value = []
  visible.value = false
}
</script>

<style lang="scss" scoped>
.pagination {
  margin-top: 15px;
}
</style>
